# -*- coding: utf-8 -*-

from odoo import models, fields, api, exceptions,_
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT


class HrAttendance(models.Model):
    _inherit = 'hr.attendance'

    _order = 'date desc'

    def name_get(self):
        result = []
        for attendance in self:

            if not attendance.check_out or not attendance.check_in:
                result.append((attendance.id, _("%(empl_name)s") % {
                    'empl_name': attendance.employee_id.name,
                }))
            else:
                result.append((attendance.id, _("%(empl_name)s from %(check_in)s to %(check_out)s") % {
                    'empl_name': attendance.employee_id.name,
                    'check_in': fields.Datetime.to_string(fields.Datetime.context_timestamp(attendance, fields.Datetime.from_string(attendance.check_in))),
                    'check_out': fields.Datetime.to_string(fields.Datetime.context_timestamp(attendance, fields.Datetime.from_string(attendance.check_out))),
                }))
        return result

    date = fields.Date(string=u'日期')
    check_in=fields.Datetime(compute='compute_check_time')
    check_out=fields.Datetime(compute='compute_check_time')
    department_id=fields.Many2one('hr.department',compute='compute_department_id',store=True,string=u'部门')
    barcode=fields.Char(related='employee_id.barcode',string=u'工号')
    employee_type = fields.Selection([
        ('1', '月薪'),
        ('2', '日薪'),
        ('3', '小时工')
    ], string=u'职工类型',related='employee_id.employee_type')
    production_line_id = fields.Many2one('hr.production.line', string='线别', related='employee_id.production_line_id')
    @api.depends('employee_id')
    def compute_department_id(self):
        for r in self:
            r.department_id=r.employee_id.department_id
    @api.depends('check_in', 'check_out')
    def _compute_worked_hours(self):
        for attendance in self:
            if attendance.check_out and  attendance.check_in:
                delta = attendance.check_out - attendance.check_in
                attendance.worked_hours = delta.total_seconds() / 3600.0
            else:
                attendance.worked_hours = False

    record_info=fields.Char(compute='compute_record_info',string=u'当天所有刷卡记录')

    def compute_record_info(self):
        for record in self:
            if record.record_ids:
                record.record_info='  ;  '.join(r.card_date_time.strftime(DEFAULT_SERVER_DATETIME_FORMAT).split(' ')[1] for r in record.record_ids.sorted('card_date_time'))
            else:
                record.record_info=''

    record_ids=fields.One2many('hr.record','attendance_id')
    resource_calendar_id=fields.Many2one('resource.calendar',compute='compute_resource_calendar_id')
    @api.depends('date','employee_id')
    def compute_resource_calendar_id(self):
        for record in self:
           record.resource_calendar_id=record.employee_id.get_current_calendar_id(record.date)
    @api.depends('record_ids')
    def compute_check_time(self):
        for record in self:
            calendar = record.employee_id.get_current_calendar_id(record.date)
            recheck=False
            if len(record.record_ids)>1:
                period=(record.record_ids[0].card_date_time-record.record_ids[-1].card_date_time).seconds
                if period<3600:
                    recheck=True




            if not calendar:
                record.check_in = ''
                record.check_out = ''
            elif len(record.record_ids)==1:
                if calendar.calendar_type=='3':
                    hour_from = calendar.attendance_ids[1].hour_from
                    hour_to = calendar.attendance_ids[0].hour_to
                else:
                    hour_from = calendar.attendance_ids[0].hour_from
                    hour_to = calendar.attendance_ids[1].hour_to
                date_time=record.record_ids[0].card_date_time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
                time = date_time.split(' ')[1]
                date = date_time.split(' ')[0]
                h, m, s = time.split(':')
                if int(m) >= 30:
                    m = '.5'
                    hh = float(h) + float(m)
                else:
                    hh = int(h)
                if abs(float(hh)-float(hour_from))<=abs(float(hh)-float(hour_to)):
                    record.check_in = record.record_ids[-1].show_card_date_time
                    record.check_out=0
                else:
                    record.check_out = record.record_ids[-1].show_card_date_time
                    record.check_in=0
            elif len(record.record_ids)>1 and recheck:
                # 如果夜班打开时间小于1小时，早上最后一笔打卡是下班
                calendar_id=record.employee_id.get_current_calendar_id(record.date)
                if calendar_id.calendar_type=='3':
                    hour_from = calendar.attendance_ids[1].hour_from
                    hour_to = calendar.attendance_ids[0].hour_to
                    date_time = record.record_ids[0].card_date_time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
                    time = date_time.split(' ')[1]
                    date = date_time.split(' ')[0]
                    h, m, s = time.split(':')
                    if int(m) >= 30:
                        m = '.5'
                        hh = float(h) + float(m)
                    else:
                        hh = int(h)
                    if abs(float(hh) - float(hour_from)) <= abs(float(hh) - float(hour_to)):
                        record.check_in = record.record_ids[0].show_card_date_time
                        record.check_out = 0
                    else:
                        record.check_out = record.record_ids[0].show_card_date_time
                        record.check_in = 0
                else:
                    hour_from = calendar.attendance_ids[0].hour_from
                    hour_to = calendar.attendance_ids[1].hour_to
                    date_time=record.record_ids[0].card_date_time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
                    time = date_time.split(' ')[1]
                    date = date_time.split(' ')[0]
                    h, m, s = time.split(':')
                    if int(m) >= 30:
                        m = '.5'
                        hh = float(h) + float(m)
                    else:
                        hh = int(h)
                    if abs(float(hh)-float(hour_from))<=abs(float(hh)-float(hour_to)):
                        record.check_in = record.record_ids[-1].show_card_date_time
                        record.check_out=0
                    else:
                        record.check_out = record.record_ids[-1].show_card_date_time
                        record.check_in=0


            elif  record.record_ids and record.employee_id.employee_type==1:
                record.check_in=record.record_ids[-1].card_date_time
                record.check_out=record.record_ids[0].card_date_time
            elif record.record_ids:
                record.check_in = record.record_ids[-1].show_card_date_time
                record.check_out = record.record_ids[0].show_card_date_time
            else:
                record.check_in =''
                record.check_out=''


    def compute_check_time_v2(self):
        calendar = self.employee_id.get_current_calendar_id(self.date)
        periods=calendar.get_time_p




    def compute_check_time_v4(self):
      pass

    def compute_check_time_v6(self):
      pass



    @api.constrains('check_in', 'check_out', 'employee_id')
    def _check_validity(self):
        """ Verifies the validity of the attendance record compared to the others from the same employee.
            For the same employee we must have :
                * maximum 1 "open" attendance record (without check_out)
                * no overlapping time slices with previous employee records
        """
        for attendance in self:
            # we take the latest attendance before our check_in time and check it doesn't overlap with ours
            last_attendance_before_check_in = self.env['hr.attendance'].search([
                ('employee_id', '=', attendance.employee_id.id),
                ('check_in', '<=', attendance.check_in),
                ('id', '!=', attendance.id),
            ], order='check_in desc', limit=1)
            if attendance.check_in and last_attendance_before_check_in and last_attendance_before_check_in.check_out and last_attendance_before_check_in.check_out > attendance.check_in:
                raise exceptions.ValidationError(_(
                    "Cannot create new attendance record for %(empl_name)s, the employee was already checked in on %(datetime)s") % {
                                                     'empl_name': attendance.employee_id.name,
                                                     'datetime': fields.Datetime.to_string(
                                                         fields.Datetime.context_timestamp(self,
                                                                                           fields.Datetime.from_string(
                                                                                               attendance.check_in))),
                                                 })

            if not attendance.check_out:
                # if our attendance is "open" (no check_out), we verify there is no other "open" attendance
                no_check_out_attendances = self.env['hr.attendance'].search([
                    ('employee_id', '=', attendance.employee_id.id),
                    ('check_out', '=', False),
                    ('id', '!=', attendance.id),
                ], order='check_in desc', limit=1)
                if no_check_out_attendances:
                    pass
                    # raise exceptions.ValidationError(_(
                    #     "Cannot create new attendance record for %(empl_name)s, the employee hasn't checked out since %(datetime)s") % {
                    #                                      'empl_name': attendance.employee_id.name,
                    #                                      'datetime': fields.Datetime.to_string(
                    #                                          fields.Datetime.context_timestamp(self,
                    #                                                                            fields.Datetime.from_string(
                    #                                                                                no_check_out_attendances.check_in))),
                    #                                  })
            else:
                # we verify that the latest attendance with check_in time before our check_out time
                # is the same as the one before our check_in time computed before, otherwise it overlaps
                last_attendance_before_check_out = self.env['hr.attendance'].search([
                    ('employee_id', '=', attendance.employee_id.id),
                    ('check_in', '<', attendance.check_out),
                    ('id', '!=', attendance.id),
                ], order='check_in desc', limit=1)
                if last_attendance_before_check_out and last_attendance_before_check_in != last_attendance_before_check_out:
                    raise exceptions.ValidationError(_(
                        "Cannot create new attendance record for %(empl_name)s, the employee was already checked in on %(datetime)s") % {
                                                         'empl_name': attendance.employee_id.name,
                                                         'datetime': fields.Datetime.to_string(
                                                             fields.Datetime.context_timestamp(self,
                                                                                               fields.Datetime.from_string(
                                                                                                   last_attendance_before_check_out.check_in))),
                                                     })
